<template>
	<div class="page-info">
		<div class="search">
			<div class="search-box">
				<a-form
					:model="searchInfo"
					:label-col="labelCol"
					:wrapper-col="wrapperCol"
				>
					<a-row :gutter="24">
						<a-col :span="8">
							<a-form-item :name="'type'" label="用户类型">
								<a-select
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.type"
									allow-clear
									placeholder="请选择用户类型"
								>
									<a-select-option value="">全部</a-select-option>
									<a-select-option value="member">会员</a-select-option>
									<a-select-option value="matchmaker">红娘</a-select-option>
									<a-select-option value="partner">合伙人</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item
								:name="labelMap['nickname'].name"
								:label="labelMap['nickname'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.nickname"
									:placeholder="'请填写' + labelMap['nickname'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col style="text-align: right; margin-bottom: 20px">
							<a-space>
								<a-button type="primary" @click="query"> 查找</a-button>
								<a-button type="primary" @click="cancelQuery">清空</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
		</div>
		<div class="button" style="margin: 10px">
			<a-space>
				<!-- <a-button type="primary" @click="editUserProfileInfo('add')">新增</a-button> -->
				<a-button type="primary" @click="exportUserProfileInfoData"
					>导出</a-button
				>
				<a-button type="primary" danger @click="batchDelUserProfileInfo"
					>删除</a-button
				>
			</a-space>
		</div>
		<div class="content">
			<a-table
				:dataSource="dataSource"
				:columns="columns"
				:loading="loading"
				:row-key="(record) => record.id"
				:pagination="pagination"
				@change="handleTableChange"
				:scroll="{ x: 'max-content', y: 425 }"
				:row-selection="rowSelection"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'operation'">
						<a-space>
							<!-- <a-button type="primary" size="small" @click="editUserProfileInfo('update', record.id)">编辑</a-button> -->
							<a-popconfirm
								v-if="record.id != 1"
								title="确认删除?"
								ok-text="确认"
								cancel-text="取消"
								@confirm="delUserProfileInfo(record.id)"
								@cancel="cancel"
							>
								<a-button type="primary" size="small" danger>删除</a-button>
							</a-popconfirm>
						</a-space>
						<span></span>
					</template>
					<template v-else-if="column.key === 'gender'">
						{{ record?.gender === '0' ? '男' : '女' }}
					</template>
					<template v-else-if="column.key === 'residenceName'">
						{{ record.provinceName }}/{{ record.cityName }}/{{
							record.districtName
						}}
					</template>
					<template v-else-if="column.key === 'identityName'">
						{{ record?.identityVerificationVo?.name || '-' }}
					</template>
					<template v-else-if="column.key === 'membershipFlag'">
						<a-tag :color="record?.membershipFlag ? 'green' : 'default'">
							{{ record?.membershipFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'membershipName'">
						{{ record.membershipName || '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerFlag'">
						<a-tag :color="record?.matchmakerFlag ? 'green' : 'default'">
							{{ record?.matchmakerFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'partnerFlag'">
						<a-tag :color="record?.partnerFlag ? 'green' : 'default'">
							{{ record?.partnerFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'membershipExpireTime'">
						{{
							record?.userMembershipInfoVo?.endTime ?
								dayjs(record?.userMembershipInfoVo?.endTime).format(
									'YYYY-MM-DD',
								)
							:	'-'
						}}
					</template>
					<template v-else-if="column.key === 'matchmakerName'">
						{{ record?.matchmakerInfoVo?.positionLevel || '-' }}
					</template>
					<template v-else-if="column.key === 'partnerTypeName'">
						{{
							getPartnerName(record?.offlineServiceProviderVo?.partnerType) ||
							'-'
						}}
					</template>
					<template v-else-if="column.key === 'partnerExpireTime'">
						{{
							record?.offlineServiceProviderVo?.endTime ?
								dayjs(record.offlineServiceProviderVo?.endTime).format(
									'YYYY-MM-DD',
								)
							:	'-'
						}}
					</template>
				</template>
			</a-table>
			<UserProfileInfoDetail
				ref="editInfo"
				:open="visible"
				:modelInfo="modelInfo"
				@handleOk="handleOk"
				@handleCancel="handleCancel"
			></UserProfileInfoDetail>
		</div>
	</div>
</template>
<script setup lang="ts">
import { columns, DataItem, ModelInfo, pageInfo, pagination, SearchInfo } from './userProfileInfoListTs';
import {
	deleteUserProfileInfo,
	exportUserProfileInfo,
	getUserProfileInfoPage,
} from '@/api/userInfo/userProfileInfo/userProfileInfoTs';
import { message } from 'ant-design-vue';
import { getDictList } from '@/api/commonInfo/dictInfo/dictInfoTs';
import { dictInfo } from '@/views/commonInfo/dictInfo/dictInfoListTs';
import dayjs from 'dayjs';
import { getPartnerName } from '@/utils/common';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let rowIds = [] as any;

const rowSelection = ref({
	checkStrictly: false,
	onChange: (
		selectedRowKeys: (string | number)[],
		selectedRows: DataItem[],
	) => {
		rowIds = selectedRowKeys;
	},
	onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (
		selected: boolean,
		selectedRows: DataItem[],
		changeRows: DataItem[],
	) => {
		console.log(selected, selectedRows, changeRows);
	},
});

const labelMap = ref<any>({
	nickname: { name: 'nickname', label: '昵称' },
	gender: { name: 'gender', label: '性别' },
	birthYearMonth: { name: 'birthYearMonth', label: '出生年月' },
	height: { name: 'height', label: '身高 (单位: cm)' },
	weight: { name: 'weight', label: '体重 (单位: kg)' },
	residence: { name: 'residence', label: '居住所在地' },
	maritalStatus: { name: 'maritalStatus', label: '婚姻状况' },
	educationLevel: { name: 'educationLevel', label: '最高学历/文化层次' },
	profession: { name: 'profession', label: '从事行业/职业' },
	incomeStatus: { name: 'incomeStatus', label: '年收入' },
	carHouseStatus: { name: 'carHouseStatus', label: '车房情况' },
	specialNote: { name: 'specialNote', label: '特殊说明' },
	partnerRequirements: { name: 'partnerRequirements', label: '择偶要求' },
	loveView: { name: 'loveView', label: '我的爱情观' },
	idealPartner: { name: 'idealPartner', label: '理想中的Ta' },
	contactPhone: { name: 'contactPhone', label: '联系方式' },
	avatarIds: { name: 'avatarIds', label: '个人形象照片ID, 多个ID用逗号隔开' },
	userId: { name: 'userId', label: '用户id' },
	zodiac: { name: 'zodiac', label: '星座' },
	cnZodiac: { name: 'cnZodiac', label: '属相' },
	school: { name: 'school', label: '学校' },
	educationType: { name: 'educationType', label: '教育类型' },
});

let searchInfo = ref<SearchInfo>({});

let genderList = ref<dictInfo[]>([]);
let residenceList = ref<dictInfo[]>([]);
let maritalStatusList = ref<dictInfo[]>([]);
let educationLevelList = ref<dictInfo[]>([]);
let professionList = ref<dictInfo[]>([]);
let incomeStatusList = ref<dictInfo[]>([]);
let carHouseStatusList = ref<dictInfo[]>([]);
let zodiacList = ref<dictInfo[]>([]);
let cnZodiacList = ref<dictInfo[]>([]);
let schoolList = ref<dictInfo[]>([]);
let educationTypeList = ref<dictInfo[]>([]);

const getDictInfoList = (): void => {
	getDictList(
		'educationType,educationType,educationType,educationType,educationType,educationType,educationType,educationType,educationType,school,educationType',
	).then((res) => {
		if (res.code == '200') {
			genderList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			residenceList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			maritalStatusList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			educationLevelList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			professionList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			incomeStatusList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			carHouseStatusList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			zodiacList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			cnZodiacList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
			schoolList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'school',
			);
			educationTypeList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'educationType',
			);
		} else {
			message.error((res && res.message) || '查询列表失败！');
		}
	});
};

const cancelQuery = (): void => {
	searchInfo.value = {};
};

const query = (): void => {
	getUserProfileInfoListPage(searchInfo.value, pagination.value);
};

const handleTableChange = (pagination): void => {
	getUserProfileInfoListPage(searchInfo.value, pagination);
};

const delUserProfileInfo = (ids: string): void => {
	deleteUserProfileInfo(ids).then((res) => {
		if (res.code == '200') {
			message.success((res && '删除' + res.message) || '删除成功！', 3);
			getUserProfileInfoListPage(searchInfo.value, pagination.value);
		} else {
			message.error((res && res.message) || '删除失败！', 3);
		}
	});
};

const batchDelUserProfileInfo = (): void => {
	let ids = '';
	if (rowIds && rowIds.length > 0) {
		rowIds.forEach((item: string) => {
			ids += item + ',';
		});
		ids = ids.substring(0, ids.length - 1);
	} else {
		message.warning('请先选择数据！', 3);
		return;
	}
	delUserProfileInfo(ids);
};

let loading = ref<boolean>(false);

let dataSource = ref();

const cancel = (e: MouseEvent): void => {
	console.log(e);
};

const getUserProfileInfoListPage = (param: SearchInfo, cur: pageInfo): void => {
	loading.value = true;
	getUserProfileInfoPage(param, cur.current, cur.pageSize)
		.then((res: any) => {
			if (res.code == '200') {
				dataSource.value = res.data.records;
				pagination.value.current = res.data.current;
				pagination.value.pageSize = res.data.size;
				pagination.value.total = res.data.total;
			} else {
				message.error((res && res.message) || '查询列表失败！');
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

const init = (): void => {
	getDictInfoList();
	//获取用户档案表页面数据
	getUserProfileInfoListPage(searchInfo.value, pagination.value);
};

init();

let visible = ref<boolean>(false);

let modelInfo = ref<ModelInfo>({});

//新增和修改弹窗
const editUserProfileInfo = (type: string, id?: number): void => {
	if (type == 'add') {
		modelInfo.value.title = '新增明细';
		modelInfo.value.id = undefined;
	} else if (type == 'update') {
		modelInfo.value.title = '修改明细';
		modelInfo.value.id = id;
	}
	modelInfo.value.confirmLoading = true;
	visible.value = true;
};

const handleOk = (v: boolean): void => {
	visible.value = v;
	getUserProfileInfoListPage(searchInfo.value, pagination.value);
};

const handleCancel = (v: boolean): void => {
	visible.value = v;
};

const exportUserProfileInfoData = () => {
	exportUserProfileInfo(searchInfo.value, { responseType: 'blob' })
		.then((response: any) => {
			const blob = new Blob([response.data], {
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			});
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement('a');
			link.href = url;
			link.setAttribute('download', '用户档案列表.xlsx');
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(url);
		})
		.catch((error: any) => {
			console.error('Error exporting Excel:', error);
		});
};
</script>
<style lang="scss" scoped></style>
